from uvicorn import server
import webview
import threading
import os
import json
from backend.main import app
import uvicorn

def find_available_port(start_port=8028):
    import socket
    port = start_port
    while True:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            try:
                s.bind(('localhost', port))
                return port
            except OSError:
                port += 1
      
if __name__ == '__main__':
    # 启动前端时传递环境变量
    server_port = find_available_port()
    # 启动FastAPI服务器
    server_thread = threading.Thread(target=uvicorn.run, kwargs={
        'app': app, 
        'host': 'localhost', 
        'port':server_port,
        'proxy_headers': True,  # 添加代理头支持
        'log_level': 'debug'
    }, daemon=True)
    server_thread.start()
   
    print(f"API启动成功: http://localhost:{server_port}")  # 添加成功日志
    
    # 确定要加载的URL
    
    print(f"正在加载页面")  # 添加日志输出
    url = f"http://localhost:{server_port}"

 
    # 读取应用配置

    try:
        with open('app-config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
            print(f"加载配置：{config}")  # 添加日志输出
        app_config = config['app']
        window_config = app_config['window']
        # 确保min_size是元组类型
        if isinstance(window_config['minSize'], list):
            window_config['minSize'] = tuple(window_config['minSize'])
    except Exception as e:
        print(f"读取配置文件失败: {e}")
        window_config = {
            'title': '一体化桌面应用',
            'width': 1024,
            'height': 800,
            'minSize': (1024, 800),
            'resizable': True,
            'text_select': True,
            'easy_drag': True,
            'debug': False
        }

    # 创建窗口
    window = webview.create_window(
        window_config['title'],
        url,
        width=window_config['width'],
        height=window_config['height'],
        min_size=window_config['minSize'],
        resizable=window_config['resizable'],
        text_select=window_config['text_select'],
        easy_drag=window_config['easy_drag']
    )
       
    # 启动WebView
    webview.start(debug=window_config['debug'])
